<template>
  <div class="galvanizeteam-container">
    <!-- 顶部标题 -->
    <el-row justify="center" class="header-row">
      <el-col :span="24" class="title">镀锌班组报表概览</el-col>
    </el-row>

    <!-- 主要统计表格 -->
    <el-row :gutter="16" class="main-tables">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-title">质量</div>
          <el-table :data="qualityData" border size="small">
            <el-table-column prop="demotion" label="降级(吨)" />
            <el-table-column prop="sealing" label="封闭" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="9">
        <el-card shadow="hover" class="stat-card">
          <div class="card-title">产量</div>
          <el-table :data="productionData" border size="small">
            <el-table-column prop="planoutput" label="计划产量" />
            <el-table-column prop="activeoutput" label="实际产量" />
            <el-table-column prop="capacityfactor" label="产能利用率" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="9">
        <el-card shadow="hover" class="stat-card">
          <div class="card-title">成材率</div>
          <el-table :data="yieldData" border size="small">
            <el-table-column prop="actualyieldrate" label="当日实际成材率" />
            <el-table-column prop="abnormalshearing" label="异常剪切(吨)" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 停机统计、降级统计、头尾异常统计 -->
    <el-row :gutter="16" class="sub-tables">
      <el-col :span="24">
        <el-card shadow="hover" class="stat-card">
          <div class="card-title">停机统计</div>
          <el-table :data="stopData" border size="small">
            <el-table-column prop="period" label="小停机时段" />
            <el-table-column prop="duration" label="修机时长(分)" />
            <el-table-column prop="affectoutput" label="影响产量(吨)" />
            <el-table-column label="停机造成降级品说明" align="center">
              <el-table-column prop="steelgrade" label="钢种" />
              <el-table-column prop="thickness" label="厚度" />
              <el-table-column prop="width" label="宽度" />
              <el-table-column prop="weight" label="重量(吨)" />
            </el-table-column>
            <el-table-column prop="reason" label="停机原因描述" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 绿色大数据条 -->
    <el-row class="green-bar-row">
      <el-col :span="24">
        <div class="green-bar">
          <div class="green-bar-item" v-for="item in greenBarData" :key="item.label">
            <div class="green-bar-label">{{ item.label }}</div>
            <div class="green-bar-value">{{ item.value }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 设备功能统计及需协调事项 -->
    <el-row class="device-issue-row">
      <el-col :span="12">
        <el-card shadow="hover" class="device-issue-card">
          <div class="card-title">设备功能统计及需协调事项</div>
          <div class="device-issue-content">
            <b>电气故障：</b
            >炼钢厂电气设备众多，包括电机、变压器、配电柜等。由于生产环境潮湿、粉尘多，电气元件易受潮、积尘，导致绝缘性能下降，引发短路、漏电等故障。例如，电机的绕组因长期处于恶劣环境，绝缘层老化，可能出现间短路，使电机无法正常运转。此外，电气系统的线路接点在长期运行中可能松动，造成接触不良，影响设备的正常供电。
          </div>
        </el-card>
        <el-card>
          <el-tabs v-model="fakeActiveTab">
            <el-tab-pane label="外板每两小时总结" name="outPlate">
              <div class="outPlate-content">
                <div>
                  <el-row :gutter="8">
                    <el-col :span="12">
                      <div style="display: flex; flex-wrap: nowrap; align-items: center; gap: 12px">
                        <el-date-picker
                          v-model="start"
                          type="datetime"
                          placeholder="开始时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          style="min-width: 160px"
                          size="small"
                        />
                        <span>至</span>
                        <el-date-picker
                          v-model="end"
                          type="datetime"
                          placeholder="结束时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          style="min-width: 160px"
                          size="small"
                        />
                      </div>
                    </el-col>
                    <el-col :span="4">
                      <el-button type="primary" size="small" @click="fetchOutPlate">查询</el-button>
                      <el-button size="small" @click="resetOutput">重置</el-button>
                    </el-col>
                  </el-row>
                </div>
                <div>
                  <el-table :data="outPlateTableData" v-if="outPlateTableData.length > 0" size="small">
                    <el-table-column prop="inputAmount" label="投入量" min-width="120px" align="center" />
                    <el-table-column prop="outputAmount" label="产出量" min-width="120px" align="center" />
                    <el-table-column prop="throughputRate" label="直通率" align="center" />
                    <el-table-column prop="firstPassYield" label="一次合格率" min-width="120px" align="center" />
                    <el-table-column prop="inRate" label="内部合格率" min-width="120px" align="center" />
                    <el-table-column prop="closeAmount">
                      <template #header>
                        <span>封闭量: </span>
                        <span class="outPlate-number">
                          {{ outPlateTableData[0]?.enclosed }}
                        </span>
                      </template>
                      <el-table-column
                        v-for="col in enclosedDetail"
                        :key="col.prop"
                        :prop="col.prop"
                        :label="col.label"
                        align="center"
                        min-width="120px"
                      />
                    </el-table-column>
                    <!-- :label="'降级量: ' + outPlateTableData[0].downgraded" :label="'封闭量: ' + outPlateTableData[0].enclosed"-->
                    <el-table-column prop="downgradeAmount">
                      <template #header>
                        <span>降级量: </span>
                        <span class="outPlate-number">
                          {{ outPlateTableData[0]?.downgraded }}
                        </span>
                      </template>
                      <el-table-column
                        v-for="col in downgradedDetail"
                        :key="col.prop"
                        :prop="col.prop"
                        :label="col.label"
                        align="center"
                        min-width="120px"
                      />
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="device-issue-card">
          <div class="card-title">月汇总热力图</div>
          <div class="device-issue-content">
            <VChart :option="heatmapOption" autoresize style="width: 100%; height: 320px" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 下方tab和数据表格 -->
    <el-card class="bottom-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="缺陷明细汇总" name="defect">
          <el-row :gutter="8" class="search-bar">
            <el-col :span="6">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                size="small"
                style="width: 100%"
              />
            </el-col>
            <el-col :span="6">
              <el-input v-model="searchText" placeholder="请输入关键字" size="small" />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" size="small">查询</el-button>
              <el-button size="small">重置</el-button>
            </el-col>
          </el-row>
          <el-table :data="mainTableData" border size="small" style="margin-top: 10px">
            <el-table-column prop="team" label="班组" />
            <el-table-column prop="defect" label="缺陷" />
            <el-table-column prop="owner" label="归户" />
            <el-table-column prop="serial" label="卷号" />
            <el-table-column prop="weight" label="重量(吨)" />
            <el-table-column prop="time" label="镀锌生产时间" />
            <el-table-column prop="steel" label="钢种" />
            <el-table-column prop="thickness" label="订厚度" />
            <el-table-column prop="width" label="订宽度" />
            <el-table-column prop="diff" label="缺陷产生排除备注" />
          </el-table>
        </el-tab-pane>
        <!-- 可扩展更多tab -->
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, nextTick, ref, watch, computed, onBeforeUnmount } from 'vue';
  import { EChartsOption } from 'echarts';
  import VChart from 'vue-echarts';
  import dayjs from 'dayjs';
  import { galvanizeApi } from '/@/api/report/index';

  // 热力图详细数据映射
  const heatmapDetails = [
    // 链轧生产
    { y: 0, x: 0, value: 136, team: '丁班组', type: '链轧生产', percent: '68%', defect: 4 },
    { y: 0, x: 1, value: 120, team: '丙班组', type: '链轧生产', percent: '60%', defect: 3 },
    { y: 0, x: 2, value: 130, team: '乙班组', type: '链轧生产', percent: '65%', defect: 4 },
    { y: 0, x: 3, value: 140, team: '甲班组', type: '链轧生产', percent: '70%', defect: 5 },
    // 设备
    { y: 1, x: 0, value: 44, team: '丁班组', type: '设备', percent: '22%', defect: 2 },
    { y: 1, x: 1, value: 60, team: '丙班组', type: '设备', percent: '30%', defect: 2 },
    { y: 1, x: 2, value: 50, team: '乙班组', type: '设备', percent: '25%', defect: 3 },
    { y: 1, x: 3, value: 40, team: '甲班组', type: '设备', percent: '20%', defect: 2 },
    // 其他
    { y: 2, x: 0, value: 20, team: '丁班组', type: '其他', percent: '10%', defect: 1 },
    { y: 2, x: 1, value: 20, team: '丙班组', type: '其他', percent: '10%', defect: 1 },
    { y: 2, x: 2, value: 20, team: '乙班组', type: '其他', percent: '10%', defect: 1 },
    { y: 2, x: 3, value: 20, team: '甲班组', type: '其他', percent: '10%', defect: 1 },
  ];

  const heatmapOption: EChartsOption = {
    tooltip: {
      formatter: (params: any) => {
        console.log('params' + params);
        const d = heatmapDetails.find((item) => item.x === params.value[1] && item.y === params.value[0]);
        if (d) {
          return `${d.type} - ${d.team}：数量 ${d.value}，占比 ${d.percent}，缺陷数${d.defect}`;
        }
        return '';
      },
    },
    grid: { left: 80, right: 20, top: 30, bottom: 40 },
    xAxis: {
      type: 'category',
      data: ['链轧生产', '设备', '其他'],
      splitArea: { show: true },
      axisLabel: { fontSize: 14 },
    },
    yAxis: {
      type: 'category',
      data: ['丁班组', '丙班组', '乙班组', '甲班组'],
      splitArea: { show: true },
      axisLabel: { fontSize: 14 },
    },
    visualMap: {
      min: 0,
      max: 140,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 270,
    },
    series: [
      {
        name: '月汇总',
        type: 'heatmap',
        data: heatmapDetails.map((d) => [d.y, d.x, d.value]),
        label: {
          show: true,
          formatter: (params: any) => {
            const d = heatmapDetails.find((item) => item.x === params.value[1] && item.y === params.value[0]);
            if (d) {
              return `数量: ${d.value}, 占比: ${d.percent}, 缺陷: ${d.defect}`;
            }
            return '';
          },
          color: '#222',
          fontSize: 13,
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.3)',
          },
        },
      },
    ],
  };

  const qualityData = [
    { demotion: 1, sealing: 2 },
    { demotion: 0, sealing: 1 },
  ];
  const productionData = [
    { planoutput: 100, activeoutput: 110, capacityfactor: '97%' },
    { planoutput: 98, activeoutput: 112, capacityfactor: '96%' },
  ];
  const yieldData = [
    { actualyieldrate: '98%', abnormalshearing: 1.3 },
    { actualyieldrate: '97%', abnormalshearing: 1.1 },
  ];
  const stopData = [
    { period: '08:00-10:00', duration: 30, affectoutput: 10 },
    { period: '10:30-11:00', duration: 20, affectoutput: 8 },
  ];
  const downgradingData = [
    { steel: 'Q235', thickness: '1.2', width: '1000', weight: 2.5, desc: '表面缺陷' },
    { steel: 'Q345', thickness: '1.5', width: '1200', weight: 1.8, desc: '厚度不均' },
  ];
  const abnormalData = [
    { steel: 'Q235', thickness: '1.2', width: '1000', weight: 0.5, desc: '头部异常' },
    { steel: 'Q345', thickness: '1.5', width: '1200', weight: 0.8, desc: '尾部异常' },
  ];
  const greenBarData = [
    { label: '厂内指标', value: '0.15%' },
    { label: '日废次降率', value: '0.81%' },
    { label: '月累计废次降率', value: '0.51%' },
    { label: '有效合同追', value: '86.60%' },
    { label: '直通率', value: '45.68%' },
  ];
  const mainTableData = [
    { team: '甲班', defect: '', owner: '', serial: '', weight: '', time: '', steel: '', thickness: '', width: '', diff: '' },
    { team: '乙班', defect: '', owner: '', serial: '', weight: '', time: '', steel: '', thickness: '', width: '', diff: '' },
    { team: '丙班', defect: '', owner: '', serial: '', weight: '', time: '', steel: '', thickness: '', width: '', diff: '' },
    { team: '丁班', defect: '', owner: '', serial: '', weight: '', time: '', steel: '', thickness: '', width: '', diff: '' },
  ];
  const activeTab = ref('defect');
  const dateRange = ref([]);
  const searchText = ref('');
  const fakeActiveTab = ref('outPlate');
  // const dateRangeOutPlate = ref<any>([]);
  const start = ref();
  const end = ref();
  const outPlateTableData = ref<any>([]);
  const downgradedDetail = ref<any>([]);
  const enclosedDetail = ref<any>([]);

  //外板时间范围初始化
  const resetOutput = () => {
    // dateRangeOutPlate.value = [
    start.value = dayjs().subtract(3, 'hours').format('YYYY-MM-DD HH:mm:ss');
    end.value = dayjs().subtract(1, 'hours').format('YYYY-MM-DD HH:mm:ss');
    // ];
  };

  const fetchOutPlate = async () => {
    try {
      // let [startDate, endDate] = dateRangeOutPlate.value;
      const param = {
        startTime: start.value,
        endTime: end.value,
      };
      const res = await galvanizeApi.get1870twoHour(start.value, end.value);
      const tableData = res.data.data;

      // 构造表格行数据（只有一个对象，因为表格只有一行）
      const rowData = {
        inputAmount: tableData.inputAmount,
        outputAmount: tableData.outputAmount,
        throughputRate: (tableData.throughputRate * 100).toFixed(2) + '%',
        firstPassYield: (tableData.firstPassYield * 100).toFixed(2) + '%',
        inRate: (tableData.inRate * 100).toFixed(2) + '%',
        enclosed: tableData.enclosed, // 封闭量总值
        downgraded: tableData.downgraded, // 降级量总值
        ...tableData.enclosedDetail, // 展开封闭量详情
        ...tableData.downgradedDetail, // 展开降级量详情
      };

      // 动态生成封闭量子列配置
      const enclosedDetailColumns = Object.keys(tableData.enclosedDetail).map((key) => ({
        prop: key,
        label: key,
      }));

      // 动态生成降级量子列配置
      const downgradedDetailColumns = Object.keys(tableData.downgradedDetail).map((key) => ({
        prop: key,
        label: key,
      }));

      outPlateTableData.value = [rowData];
      enclosedDetail.value = enclosedDetailColumns;
      downgradedDetail.value = downgradedDetailColumns;
    } catch (err) {
      console.error('获取外板数据失败：' + err);
    }
  };

  onMounted(() => {
    // 外板时间初始化
    // dateRangeOutPlate.value = [dayjs().subtract(2, 'hours').format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')];
    resetOutput();
    fetchOutPlate();
  });
</script>
<style scoped>
  .galvanizeteam-container {
    padding: 18px 18px 0 18px;
    background: #f6f8fa;
  }
  .header-row .title {
    font-size: 2rem;
    font-weight: bold;
    color: #009966;
    letter-spacing: 0.5em;
    text-align: center;
    margin-bottom: 18px;
  }
  .card-title {
    font-weight: bold;
    font-size: 1.1rem;
    margin-bottom: 8px;
  }
  .stat-card {
    margin-bottom: 16px;
  }
  .device-issue-row {
    margin-bottom: 16px;
  }
  .device-issue-card {
    background: #fffbe6;
  }
  .device-issue-content {
    color: #333;
    font-size: 0.98rem;
    line-height: 1.7;
    margin-top: 8px;
  }
  .bottom-card {
    margin-top: 18px;
  }
  .search-bar {
    margin-bottom: 0;
  }
  .green-bar-row {
    margin: 18px 0 10px 0;
  }
  .green-bar {
    display: flex;
    background: #8fd16a;
    border-radius: 6px;
    padding: 10px 0;
    justify-content: space-around;
    align-items: center;
  }
  .green-bar-item {
    flex: 1;
    text-align: center;
  }
  .green-bar-label {
    font-size: 1.1rem;
    font-weight: bold;
  }
  .green-bar-value {
    font-size: 1.5rem;
    font-weight: bold;
    margin-top: 4px;
  }

  /* ------------------------------------------ 新增外板 ----------------------------  */
  .outPlate-content {
    display: flex;
    flex-direction: column;
    gap: 2rem;
  }

  .outPlate-number {
    color: #e66;
    font-weight: 700;
  }
</style>
